import { defineComponent } from 'vue';
import { addstore, getstoreList, delstore } from '@/api/storelist';
import { updatestore } from '@/api/storelist';
import { dayjs, ElMessageBox, ElMessage } from 'element-plus';
import type { Action } from 'element-plus';
import { ref, reactive } from 'vue';
import axios from 'axios';

export default defineComponent({
  data() {
    return {
      value: '',
      input: '',
      radio: ref(2),
      dialogFormVisible: false,
      stateform: false,
      storename: null,
      // 弹窗隐藏初始化
      // 初始化数据字段数据
      store: {
        storename: '',
        storelogo: '',
        defaultstore: '',
        Associatestore: '',
        username: '',
        userphone: '',
        wechatpaynumber: '',
        wechatAPlv2: '',
        storeaddress: '',
        selltime: '',
        storelatitude: '',
        storelongitude: '',
        license: '',
        creditcar: '',
        bankname: '',
        bankuser: '',
        banknumber: '',
        note: '',
        state: '',
        createdAt: '',
      },
      editstore: {
        storename: '',
        storelogo: '',
        defaultstore: '',
        Associatestore: '',
        username: '',
        userphone: '',
        wechatpaynumber: '',
        wechatAPlv2: '',
        storeaddress: '',
        selltime: '',
        storelatitude: '',
        storelongitude: '',
        license: '',
        creditcar: '',
        bankname: '',
        bankuser: '',
        banknumber: '',
        note: '',
        state: '',
        createdAt: '',
      },
      rules: {
        storename: [{ required: true, message: '店铺名称不能为空', trigger: 'blur' }],
        username: [{ required: true, message: '联系人姓名不能为空', trigger: 'blur' }],
        userphone: [{ required: true, message: '联系人电话不能为空', trigger: 'blur' }],
      },
      // 存储数据
      list: [],
      fileList: [],
      fileList1: [],
      limit: 10,
      page: 1,
      total: 1,
      // 编辑弹窗初始化
      showEdit: false,
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    // 编辑店铺弹窗
    openEdit(row: any) {
      this.editstore = row;
      this.showEdit = true;
    },
    // 删除店铺
    handleDel(id: number) {
      // 删除的操作一般需要二次确认 避免用户误操作
      ElMessageBox.confirm('是否确认删除"海口海甸岛店"的数据项？', '系统提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        callback: async (action: Action) => {
          if (action === 'cancel') return false;
          const res = await delstore(id);
          console.log('真正的去执行删除', res);
          if (res.status === 200) {
            this.$message.success('删除成功');
            this.getList();
          } else {
            this.$message.warning('删除失败');
          }
          return true;
        },
      });
    },
    // 编辑店铺
    async handleEidt() {
      console.log('editstore', this.editstore);
      const { id, ...postdata } = this.editstore;
      console.log('id', id);
      const res = await updatestore(id, postdata);
      console.log('res', res);
      const { status } = res;
      if (status === 200) {
        this.$message.success('修改成功');
        this.showEdit = false;
        this.getList();
      } else {
        this.$message.warning('修改失败');
      }
    },
    handeSizeChange(val: number) {
      console.log('val', val);
      // 获取的数据列数
      this.limit = val;
      this.getList();
    },
    handlePageChange(val: number) {
      // 获取是列数
      this.page = val;
      this.getList();
    },
    // 获取数据
    async getList() {
      const data = {
        $limit: this.limit,
        $skip: (this.page - 1) * this.limit,
      };
      if (this.input.trim() !== '') {
        (data as any).storename = this.input;
      }
      if (this.value !== '') {
        (data as any).state = this.value;
      }
      const res = await getstoreList(data);
      this.list = res.data.data;
      console.log(this.list);
      this.total = res.data.total;
    },
    //刷新数据
    async getListRest() {
      this.input = '';
      this.value = '';
      this.getList();
    },
    //转换时间
    formatTime(time: string) {
      return dayjs(time).format('YYYY-MM-DD HH:MM:ss');
    },
    // //   增加店铺
    async storeAdd() {
      console.log('store', this.store);
      console.log('$refs.addfrom', this.$refs.addfrom);
      try {
        const validateRes = await (this.$refs.addfrom as any).validate();
        console.log('validateRes', validateRes);
        // 确保表单完全的通过校验规则
        const res = await addstore(this.store);
        console.log('res', res);
        const { status } = res;
        if (status === 201) {
          this.$message.success('添加成功');
          this.dialogFormVisible = false;
          this.getList();
        } else {
          this.$message.warning('添加失败');
        }
      } catch (e) {
        this.$message.warning('请按要求检查表单内容');
      }
    },
    // 上传图片
    handleUpload(options: any) {
      // 实际工作当中我们更多的是自己去执行上传的具体操作 因为上传前我们还有可以需要进行压缩操作等
      //  打印查看里面的属性
      console.log('options', options);
      // options.file就是我们要上传的文件对象
      // FormData 表格类型阿贾克斯上传文件 先new 一个表格类型
      const formdata = new FormData();
      // 在调用一个方法 formdata.append 添加
      formdata.append('file', options.file); // 实践当中对于这个file对象一般还需要进行压缩处理等
      formdata.append('type', 'qf2302');
      // 引入接口上传
      // 返回一个promise对像
      return axios.post('http://www.wzsqyg.com/attachment/upload', formdata);
    },
    // 上传前的约束 自动上传
    // rawFilez 组件带的 ：类型 boolean组件要求要返回return
    beforeAvatarUpload(rawFile: any): boolean {
      // 获取的是组件中的属性值
      // 可以获取大小，名称，类型
      console.log('rawFile', rawFile);
      // 使用上传之前的钩子我们可以对于上传的文件进行检测或者大小的判断 方法点属性
      // includes 意为包含 image 图片
      // 上传类型不是图片就停止上传
      if (!rawFile.type.includes('image')) {
        this.$message.warning('只能上传图片文件');
        return false;
      }
      // 大小要转换一下 最初为bit
      //  兆 kb bit
      const min = 0.001 * 1024 * 1024;
      if (rawFile.size < min) {
        // warning 警告
        this.$message.warning('上传的图片不能小于0.2m');
        //  若返回false或者返回 Promise 且被 reject，则停止上传 组件是规定
        return false;
      }
      return true;
    },
    // respons 回调一个地址
    UploadOk(response: any) {
      console.log('response', response);
      // 将返回的值 等于商品表里面的封面
      this.store.storelogo = response.msg;
      this.store.license = response.msg;
    },
    UploadOk1(response: any) {
      console.log('response', response);
      // 将返回的值 等于商品表里面的封面
      this.store.license = response.msg;
    },
    //修改状态
    changestate(row: any, val: number, id: number) {
      if (!val) {
        console.log('启动');
        ElMessageBox.confirm(
          `确定启用"${row.storename}"吗？`,
          '系统提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          },
        )
          .then(async () => {
            console.log('点击了确认');
            this.editDengji = row;
            let { ...postdata } = this.editDengji;
            postdata.state = 1;
            await updatestore(id, postdata);
            this.getList();
            ElMessage({
              type: 'success',
              message: '启用成功',
            });
          }).catch(async () => {
            this.editDengji = row;
            let { ...postdata } = this.editDengji;
            postdata.state = 0;
            await updatestore(id, postdata);
            this.getList();
          });
      } else {
        console.log('关闭');
        ElMessageBox.confirm(
          `确定禁用"${row.storename}"吗？`,
          '系统提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          },
        )
          .then(async () => {
            this.editDengji = row;
            let { ...postdata } = this.editDengji;
            postdata.state = 0;
            await updatestore(id, postdata);
            this.getList();
            ElMessage({
              type: 'success',
              message: '禁用成功',
            });
          }).catch(async () => {
            this.editDengji = row;
            let { ...postdata } = this.editDengji;
            postdata.state = 1;
            await updatestore(id, postdata);
            this.getList();
          });
      }
    },
  },
});
